/*
 * @Author: sdq 483657864@qq.com
 * @Date: 2025-04-18 14:09:58
 * @LastEditors: sdq 483657864@qq.com
 * @LastEditTime: 2025-04-18 17:12:47
 * @FilePath: \ranyu_anchor_new\src\agroa\userPublish\index.ts
 * @Description: 推流
 */
import AgoraRTC, { ILocalAudioTrack } from "agora-rtc-sdk-ng";
import { shallowReactive } from "vue";
export const useUserPublish = async () => {
  const { agoraClient } = await import("../initAgoraSdk");
  const { handleError } = await import("../auxiliary");
  const { useAudioStore } = await import("@/store");
  const { useLiveStatusStore } = await import("@/store");
  const liveStatus = useLiveStatusStore();
  const audioStore = useAudioStore();
  /**
   * 音频设备管理（浅层响应式）
   * @property mics - 可用的麦克风设备列表
   * @property currentMic - 当前选中的麦克风设备 ID
   */
  const devices = shallowReactive<{
    mics: MediaDeviceInfo[];
    currentMic: string;
  }>({
    mics: [],
    currentMic: "",
  });
  /**
   * 加载可用的麦克风设备列表
   * @description 获取系统麦克风设备并设置默认设备
   */
  const loadDevices = async () => {
    try {
      // 获取所有麦克风设备（需要浏览器权限）
      devices.mics = await AgoraRTC.getMicrophones();

      // 设置默认设备（优先选择已授权的设备）
      const authorizedDevice = devices.mics.find((d) => d.label);
      devices.currentMic = authorizedDevice?.deviceId || devices.mics[0]?.deviceId || "";
    } catch (error) {
      handleError("设备加载失败", error);
    }
  };
  /**
   * 开启麦克风并发布音频流
   * @description 需要浏览器麦克风权限
   */
  const startMic = async () => {
    if (!liveStatus.isJoined) throw new Error("尚未加入频道");
    if (audioStore.mic || !agoraClient.value) return;
    try {
      // 创建麦克风轨道（使用当前选定设备）
      const localMic = await AgoraRTC.createMicrophoneAudioTrack({
        microphoneId: devices.currentMic,
        encoderConfig: "speech_standard",
      });
      audioStore.setMic(localMic);
      await agoraClient.value.publish(localMic);
      ElMessage.success("麦克风已开启");
    } catch (error) {
      handleError("麦克风启动失败", error);
      throw error;
    }
  };
  /**
   * 开启系统音频捕获（屏幕声音/其他应用音频）
   * @description 需要用户手动授权
   */
  const startSystemAudio = async () => {
    if (!liveStatus.isJoined) throw new Error("尚未加入频道");
    if (audioStore.system || !agoraClient.value) return;

    try {
      // 获取系统音频流（需要用户交互触发）
      const stream = await navigator.mediaDevices.getUserMedia({
        audio: true,
        video: false,
      });

      // 创建自定义音频轨道
      const localSystem = AgoraRTC.createCustomAudioTrack({
        mediaStreamTrack: stream.getAudioTracks()[0],
        encoderConfig: "speech_standard",
      });
      audioStore.setSystem(localSystem);
      // 发布到频道
      await agoraClient.value.publish(localSystem);
      ElMessage.success("系统音频已开启");
    } catch (error) {
      handleError("系统音频捕获失败", error);
      throw error;
    }
  };
  /**
   * 切换麦克风设备
   * @param deviceId - 目标设备 ID
   * @description 需要先关闭旧设备再开启新设备
   */
  const switchMic = async (deviceId: string) => {
    if (!audioStore.mic) throw new Error("麦克风未启用");
    try {
      // 取消发布并关闭旧轨道
      console.log(audioStore.mic);
      await agoraClient.value?.unpublish(audioStore.mic as ILocalAudioTrack);
      audioStore.mic.close();
      audioStore.setMic(undefined);

      // 使用新设备创建轨道
      const newLocalMic = await AgoraRTC.createMicrophoneAudioTrack({
        microphoneId: deviceId,
        encoderConfig: "speech_standard",
      });
      audioStore.setMic(newLocalMic);
      // 重新发布
      await agoraClient.value?.publish(newLocalMic);
      devices.currentMic = deviceId;
      ElMessage.success("麦克风已切换");
    } catch (error) {
      handleError("设备切换失败", error);
      throw error;
    }
  };
  return {
    startMic,
    loadDevices,
    startSystemAudio,
    switchMic,
  };
};
